const router = require('koa-router')()
const userLogin = require('../components/login')
const superagent = require('superagent')
const cheerio = require('cheerio')
const infoQuery = require('../components/infoQuery')


router.prefix('/api')


/**
 * 描述：测试功能函数接口
 */
router.get('/', async function (ctx, next) {
  let { stu, passwd } = ctx.request.query
  await infoQuery.getTodayInfo(stu, passwd)
  ctx.body = 'this is a api response!'
})


/**
 * @description 
 *     获取登录学生的基本信息
 *     使用login.js中的ehallLogin功能，得到带有cookie的agent对象，使用该对象访问接口获取学生信息
 * 
 * @response
 * {
 *    code: {int} 状态码
 *    msg: {string} 提示信息
 *    data: {
 *          userDepartment: {string} 学院
 *          userId: {string}  学号
 *          userSex: {string} 性别,
 *          userName: {string} 姓名
 *      }
 * }
 */
router.get('/getUserInfo', async function (ctx, next) {
  let { stu, passwd } = ctx.request.query
  let agent = superagent.agent()
  agent = await userLogin.ehallLogin(stu, passwd)
  if (agent) {
    await agent.get(`https://ehall.ecut.edu.cn/jsonp/userDesktopInfo.json?type=&_=${Date.now()}`).then(function (res) {
      let {
        userDepartment,
        userId,
        userSex,
        userName
      } = res.body
      ctx.body = {
        code: 200,
        msg: 'success',
        data: {
          userDepartment: userDepartment,
          userId: userId,
          userSex: userSex,
          userName: userName
        }
      }
    }).catch(err => {
      ctx.body = {
        code: 80002,
        msg: 'Interval Server Error',
        data: err
      }
    })
  } else {
    ctx.body = {
      code: 80001,
      msg: '账号或密码错误',
    }
  }

})



/**
 * @description 
 *     获取学生成绩
 *     使用login.js中的webvpn登录功能，得到带有cookie的agent对象，使用该对象访问接口获取学生信息
 * 
 * @response
 * {
 *    code: {int} 状态码
 *    msg: {string} 提示信息
 *    data: [{
 *            'cj': {number} 分数,
 *            'xf': {number} 课程学分,
 *            'jd': {number} 课程绩点,
 *            'kcxzmc': ,
 *            'kcmc': x.kcmc
 *      }...]
 * }
 */
router.get('/getScores', async function (ctx, next) {

  let { stu, passwd, xn, xq } = ctx.request.query

  let agent = await userLogin.webvpnLogin(stu, passwd)


  const getScoresUrl = `https://172-20-130-13.webvpn.ecut.edu.cn/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=${stu}`
  let postData = {
    xnm: xn,
    xqm: xq,
    _search: false,
    nd: new Date(),
    'queryModel.showCount': 100,
    'queryModel.currentPage': 1,
    'queryModel.sortName': '',
    'queryModel.sortOrder': 'asc',
    time: 1
  }
  await agent.post(getScoresUrl)
    .set('Content-Type', 'application/x-www-form-urlencoded')
    .send(postData).then(function (res) {
      console.log(res.text);
      let data = []

      JSON.parse(res.text).items.map(x => {
        data.push({
          'cj': x.bfzcj,
          'xf': x.xf,
          'jd': x.jd,
          'kcxzmc': x.kcxzmc,
          'kcmc': x.kcmc
        })
      })

      ctx.body = {
        code: 200,
        msg: 'success',
        data: data
      }
    })

})

/**
 * @description 
 *     获取学生课表
 *     使用login.js中的webvpn登录功能，得到带有cookie的agent对象，使用该对象访问接口获取学生课表
 *     
 *     旧接口,获取的是总课表
 */
router.get('/getSchedule', async function (ctx, next) {


  /*******************************旧教务系统写法********************************/
  let { stu, passwd, xq, xn } = ctx.request.query
  let agent = await userLogin.webvpnLogin(stu, passwd)

  const getScheduleUrl = `https://172-20-130-13.webvpn.ecut.edu.cn/jwglxt/kbcx/xskbcx_cxXsKb.html?gnmkdm=N2151&su=${stu}`

  let postData = {
    xnm: xn,
    xqm: xq,
    kzlx: 'ck',
    _search: false,
    nd: 1622766579564,
    'queryModel.showCount': 15,
    'queryModel.currentPage': 1,
    'queryModel.sortName': '',
    'queryModel.sortOrder': 'asc',
    time: 2
  }
  await agent.post(getScheduleUrl)
    .set('Content-Type', 'application/x-www-form-urlencoded')
    .send(postData).then(function (res) {
      let data = []

      JSON.parse(res.text).kbList.map(x => {
        data.push({
          'cdmc': x.cdmc,
          'kcmc': x.kcmc,
          'zcd': x.zcd,
          'xm': x.xm,
          'kcxz': x.kcxz,
          'xqjmc': x.xqjmc,
          'jc': x.jc
        })
      })

      ctx.body = {
        code: 200,
        msg: 'success',
        data: data
      }
    })

})




/**
 * @description 获取本周课表
 * 
 * 功能实现：主要通过两个接口实现，一个获取当日信息（包含今天是第几周，学年和学期等信息），之后通过获取的信息提交给查询每周课表的解耦
 * 
 */
router.get('/getTodaySchedule', async (ctx, next) => {
  let { stu, passwd } = ctx.request.query
  let toDayInfo = await infoQuery.getTodayInfo(stu, passwd)
  let toDaySchedule = await infoQuery.getScheduleByWeek(stu, passwd, toDayInfo.XN, toDayInfo.XQ, toDayInfo.DQZC)
  toDaySchedule.code = 200
  ctx.body = toDaySchedule;
})


/**
 * @description 获取学生电费
 */
router.get('/getUtilities', async function (ctx, next) {
  let { stu, passwd } = ctx.request.query
  let agent = superagent.agent()
  agent = await userLogin.ehallLogin(stu, passwd)
  const getUtilitiesUrl = 'https://xgwx.ecut.edu.cn/app/app/api/user/searchBindHouseListForMoney'
  let tmpUrl = ''
  await agent.get('https://authserver.ecut.edu.cn/authserver/login?service=https%3A%2F%2Fehall.ecut.edu.cn%3A443%2Fqljfwapp%2Fsys%2FxCardAppEcut%2Fmobile%2Findex.do').then(function (res) {
    console.log(res.text);
    let $ = cheerio.load(res.text)
    tmpUrl = $('a')[1].attribs.href;
  })
  await agent.get(tmpUrl).then(function (res) {
    let $ = cheerio.load(res.text)
    tmpUrl = tmpUrl.substr(0, 29) + $('a')[1].attribs.href;
  })


  await agent.get(tmpUrl)
  let postData =
  {
    userid: stu
  }
  await agent.post("https://xgwx.ecut.edu.cn:443/app/app/api/user/searchBindHouseListForMoney").set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8').send(postData).then(res => {

    let { customer_name, meter_balance } = JSON.parse(res.text).data[0].meter[0];

    ctx.body = {
      code: 200,
      msg: 'success',
      data: { customer_name, meter_balance }
    }
  })
})

/**
 * @description 通过调用建行接口查询一卡通费用
 */
router.get('/getXYK', async function (ctx, next) {
  let { stu } = ctx.request.query

  const getXYKUrl = "https://cloud.life.ccb.com/commonData/queryBillsDsf.jhtml"
  let agent = superagent.agent()
  await agent.post(getXYKUrl)
    .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    .send(`billMerchant=1724&branNo=360000000&billItem=05013&routeFlag=500100&contract_no=${stu}&remark1=&remark2=&projectSource=07&channel=4&validateCode=`).then(function (res) {
      let { itemName, itemValue } = JSON.parse(res.text).data.displayItems[0];


      ctx.body = {
        code: 200,
        msg: 'success',
        data: {
          itemName,
          itemValue
        }
      }

    })

})


module.exports = router


